package cn.lanyi.org.service.impl;

import cn.lanyi.basic.service.impl.BaseServiceImpl;
import cn.lanyi.basic.util.PageList;
import cn.lanyi.org.domain.Department;
import cn.lanyi.org.mapper.DepartmentMapper;
import cn.lanyi.org.query.DepartmentQuery;
import cn.lanyi.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

    @Override
    public List<Department> tree() {
        // 查询出所有部门
        List<Department> deptAll = mapper.loadAll();
        // 将集合转换为HashMap
        Map<Long, Department> allMap = deptAll.stream().collect(Collectors.toMap(Department::getId, item ->item));
        // 创建一个空集合 组装完成的部门树数据
        List<Department> result = new ArrayList<>();
        for (Department dept:deptAll) {
            if (null == dept.getParentId()) {
                result.add(dept);
            } else {
                Department parent = allMap.get(dept.getParentId());
                parent.getChildren().add(dept);
            }
        }
        return result;
    }
}
